<script setup lang="ts">
import { ref, watch } from "vue";
import { message } from "ant-design-vue";
import { isEmpty } from "lodash";
import { getToken } from "@/utils/auth";
import { getStyles, listProducts } from "@/apis/products";
import { setCollect, getCollect } from "@/apis/user";
import { decrypt } from "@/utils/encrypt";
import router from "@/router"; // 导入路由实例
const userProfile = ref<{ userId?: string; collect?: any[] }>({});
const isLoggedin = ref(false);
const showLoginPrompt = ref(false);
// 产品类型
const productOptions = ref<any[]>([
  {
    value: "6",
    payload: {
      typeId: "6",
      typeName: "全包围脚垫",
      typeENName: "Car Mat",
    },
  },
  {
    value: "1",
    payload: {
      typeId: "1",
      typeName: "汽车座套",
      typeENName: "Seat Cover",
    },
  },
  {
    value: "3",
    payload: {
      typeId: "3",
      typeName: "真皮座椅",
      typeENName: "Leather Seat",
    },
  },
]);

// 当前选中产品类型
const currentProduct = ref<string>(productOptions.value.at(0).value);

// 款式类型
const styleOptions = ref<any[]>([]);

// 当前选中款式类型
const currentStyle = ref<string>("");

// 产品查询条件
const queryData = ref({
  productType: "6",
  styleType: "100",
  pageIndex: 1,
  pageSize: 20,
});

// 产品数据
const products = ref<any[]>([]);

// 数据总量
const total = ref(0);

// 粘贴板内容
const clipboardTip = ref("已复制到粘贴板!");

/**
 * 获取用户信息.
 */
async function getUserProfile() {
  const token = getToken();
  if (isEmpty(token)) {
    showLoginPrompt.value = true; // 如果未登录，显示登录提示框
    return;
  }

  const userId = decrypt(token!);
  if (userId) {
    console.log("用户信息", userProfile);
    isLoggedin.value = true; // 如果已登录，设置isLoggedin为true
    userProfile.value.userId = userId;
  }
  console.log("用户信息", userProfile);
}
function handleLogin() {
  router.push({ name: "SignIn" }); // 使用路由跳转到登录页面
}
watch(
  currentProduct,
  (val) => {
    queryData.value.pageIndex = 1;
    queryData.value.pageSize = 20;
    queryData.value.productType = val;
    loadStyles(val);
  },
  {
    immediate: true,
  }
);

watch(currentStyle, (val) => {
  queryData.value.pageIndex = 1;
  queryData.value.pageSize = 20;
  queryData.value.styleType = val;
});

watch(queryData.value, loadData, {
  immediate: true,
});

/**
 * 加载数据.
 * @param {queryData.value} query
 */
async function loadData(query: typeof queryData.value) {
  try {
    const { data, totalCount } = await listProducts({ data: query });
    userProfile.value.collect = await loadUserCollections();
    const ids = userProfile.value.collect?.map<string>((e) => e.picId);
    products.value = data.map((product: any) => ({
      ...product,
      isCollected: ids?.includes(product.picId),
    }));
    total.value = totalCount;
  } catch (err) {
    console.error(err);
  }
}

/**
 * 获取款式类型
 */
async function loadStyles(productType: string) {
  try {
    const { data } = await getStyles({
      data: {
        proType: productType,
      },
    });
    // 默认样式 [全部]
    const DefaultStyle = {
      value: "100",
      payload: {
        typeId: "100",
        typeName: "全部款式",
        typeENName: "All styles",
      },
    };
    // 其他样式
    const dynamicStyle = data?.map((category: any) => ({
      value: category.typeId,
      payload: category,
    }));
    styleOptions.value = [DefaultStyle, ...dynamicStyle];
    currentStyle.value = DefaultStyle.value;
  } catch (err) {
    console.error(err);
  }
}

/**
 * 获取用户收藏列表.
 */
async function loadUserCollections() {
  if (isEmpty(userProfile.value.userId)) return;

  const response = await getCollect({
    data: {
      loginUserId: userProfile.value.userId,
      productType: queryData.value.productType,
    },
  });
  return response.data;
}

/**
 *  收藏按钮点击事件.
 * @param value
 */
async function handleColletClick(value: any) {
  if (isEmpty(userProfile.value.userId)) {
    message.info("请登录收藏");
    return;
  }

  const ids = userProfile.value.collect?.map((e) => e.picId);
  try {
    // 如果 flag 值为 -1 则取消收藏, 反之收藏
    const flag = ids?.includes(value.picId) ? -1 : 1;
    await setCollect({
      data: {
        webLoginId: userProfile.value.userId,
        carStyleId: value.picId,
        isCollection: flag,
      },
    });
    message.success(flag === 1 ? "收藏成功" : "取消收藏");
    loadData(queryData.value);
  } catch (err) {
    message.error(err as string);
  }
}

/**
 * 产品 code 存到粘贴板.
 * @param value
 */
function handleClipboardNumber(value: string) {
  navigator.clipboard
    .writeText(value)
    .then(() => {
      clipboardTip.value = "已复制到粘贴板!";
    })
    .catch((err) => {
      clipboardTip.value = `复制失败: ${err}`;
    });
}

getUserProfile();
</script>

<template>
  <div class="flex flex-col h-full bg-gray-100">
    <!-- 登录提示框 -->
    <div
      v-if="showLoginPrompt"
      class="fixed inset-0 flex items-center justify-center z-50"
    >
      <div class="bg-black opacity-50 fixed inset-0"></div>
      <!-- 遮罩层 -->
      <div
        class="bg-white p-6 rounded shadow"
        style="
          width: 14%;
          height: 18vh;
          display: flex;
          flex-direction: column;
          font-size: 1.2rem;
          justify-content: center;
          align-items: center;
          z-index: 60;
        "
      >
        <p style="font-weight: 500">请登录以查看产品</p>
        <button
          @click="handleLogin"
          class="mt-4 px-4 py-2 bg-blue-500 text-white rounded"
          style="background-color: blue; border: none"
        >
          去登录
        </button>
      </div>
    </div>

    <div class="px-12 py-3 bg-white border-0 border-b border-solid border-gray-200">
      <a-segmented class="fill" v-model:value="currentProduct" :options="productOptions">
        <template #label="{ payload }">
          <span class="flex flex-col py-1">
            <strong class="text-sm">
              {{ payload.typeName }}
            </strong>
            <small class="text-xs text-gray-500">
              {{ payload.typeENName }}
            </small>
          </span>
        </template>
      </a-segmented>
    </div>
    <div class="flex flex-nowrap items-center gap-2 px-12 py-6">
      <span class="flex-shrink-0 text-gray-400">按款式分类(By style):</span>
      <div class="category overflow-auto overscroll-contain">
        <a-segmented class="ghost" v-model:value="currentStyle" :options="styleOptions">
          <template #label="{ payload }">
            <span class="flex flex-col py-1">
              <strong class="text-sm">
                {{ payload.typeName }}
              </strong>
              <small class="text-xs text-gray-500">
                {{ payload.typeENName }}
              </small>
            </span>
          </template>
        </a-segmented>
      </div>
    </div>
    <div class="flex-1 px-12 overflow-y-scroll overscroll-contain">
      <div class="grid grid-cols-4 gap-5">
        <template v-for="product in products" :key="product?.picId">
          <a-card
            :bordered="false"
            :bodyStyle="{
              position: 'relative',
              padding: '1rem',
              overflow: 'hidden',
            }"
          >
            <a-image class="rounded-md cursor-pointer" :src="product?.smallUrl" />
            <div class="flex justify-between mt-2">
              <span class="flex flex-col space-y-2">
                <!-- <strong class="text-xl">
                                    裁剪机/震动刀专用
                                </strong> -->
                <small class="text-sm text-gray-500">
                  编号(No): {{ product.picName }}
                </small>
              </span>
              <span
                class="flex gap-x-2 text-gray-500 cursor-pointer"
                @click="() => handleColletClick(product)"
              >
                <i
                  class="like inline-block bg-gray-300"
                  :class="{ active: product.isCollected }"
                ></i>
                <span class="flex flex-col"
                  ><small>加入收藏</small> <small>Collect</small></span
                >
              </span>
            </div>
            <div class="flex gap-4 mt-4">
              <a-tooltip placement="topLeft" trigger="click" \>
                <template #title>
                  <span class="text-xs">{{ clipboardTip }}</span>
                </template>
                <a-button
                  class="flex flex-col items-center h-auto text-sm"
                  @click="() => handleClipboardNumber(product.picName)"
                >
                  <span>复制编号</span>
                  <span>Copy Number</span>
                </a-button>
              </a-tooltip>
              <a-button
                class="flex flex-col items-center h-auto text-sm"
                type="primary"
                ghost
              >
                <span>确认编号</span>
                <span>Confirmation Number</span>
              </a-button>
            </div>
            <span
              class="tag absolute top-0 right-0 z-10 flex justify-center items-center text-xs text-white"
            >
              BUY
            </span>
          </a-card>
        </template>
      </div>
    </div>
    <div class="flex justify-between items-center px-12 py-4">
      <div class="flex gap-x-6 text-gray-600">
        <span class="flex flex-col gap-y-1">
          <small>共 {{ total }} 条记录</small>
          <small>total of {{ total }} pieces</small>
        </span>
        <span class="flex flex-col gap-y-1">
          <small
            >第 {{ queryData.pageIndex }}/{{
              Math.ceil(total / queryData.pageSize)
            }}
            页</small
          >
          <small
            >page {{ queryData.pageIndex }}/{{
              Math.ceil(total / queryData.pageSize)
            }}</small
          >
        </span>
      </div>

      <a-pagination
        size="small"
        show-size-changer
        show-quick-jumper
        :pageSizeOptions="['20', '40', '60', '100']"
        v-model:current="queryData.pageIndex"
        v-model:pageSize="queryData.pageSize"
        :total="total"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.category {
  &::-webkit-scrollbar {
    width: 0.25rem;
    height: 0.25rem;
    background-color: #fff;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 0.25rem;
    background-color: rgba(0, 0, 0, 0.1);
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: rgba(0, 0, 0, 0.2);
  }

  &::-webkit-scrollbar-track-piece {
    background-color: #f5f5f5;
  }
}

.like {
  width: 23px;
  height: 22px;
  background-size: 100%;
  -webkit-mask: url("@/assets/icons/star.png") no-repeat;
  -webkit-mask-size: 100% 100%;
  mask: url("src/assets/icons/star.png") no-repeat;
  mask-size: 100% 100%;

  &.active {
    background-color: rgba(255, 77, 79, 1) !important;
  }
}

.tag {
  position: absolute;
  top: 1rem;
  right: 1rem;
  width: 44px;
  height: 40px;
  background-image: url("@/assets/icons/tag.png");
}
.bg-black.opacity-50 {
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
